package com.tensquare.web.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

//网关过滤器
@Component
public class WebFilter extends ZuulFilter {
   @Override
   //指定过滤器类型
   public String filterType() {
      //pre ：可以在请求被路由之前调用
      //route ：在路由请求时候被调用
      //post ：在route和error过滤器之后被调用
      //error ：处理请求时发生错误时被调用
      return "pre";
   }
   @Override
   //定义过滤器执行优先级
   //返回0就是最高优先级
   public int filterOrder() {
      return 0;
   }
   @Override
   //指定当前拦截器是否启用
   public boolean shouldFilter() {

      return true;
   }
   @Override
   //网管过滤器,业务逻辑代码书写在该方法中即可
   public Object run() throws ZuulException {

      //1 获得请求对象
      RequestContext requestContext = RequestContext.getCurrentContext();
      HttpServletRequest request = requestContext.getRequest();
      //2 获得Authorization头
      String authorization = request.getHeader("Authorization");
      if(!StringUtils.isEmpty(authorization)){ //Authorization头不为空
      //3 将Authorization头添加到网关转发的请求中
         requestContext.addZuulRequestHeader("Authorization",authorization);
      }
      return null;
   }
}
